package mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;


public class MyBatisDemo {

    private static SqlSessionFactory sqlSessionFactory = null;


    public static void main(String[] args) {
        String name = selectNameById(1);
        System.out.println(name);
    }



    private static String selectNameById(Integer id){
        String name = null;
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            name = mapper.selectNameById(id);
        }
        return name;
    }


    private static SqlSession openSession(){
        if (sqlSessionFactory == null) {
            try {
                InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //事务自动提交
        return sqlSessionFactory.openSession(true);
    }
}
